package wangm.nettyhttp.channelhandler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;

/**
 * describe
 *
 * @author zk
 * @date 2018-02-09 14:17
 */
public class HttpMessageServerHandler extends ChannelInboundHandlerAdapter{
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("accept msg type : " + msg.getClass().getTypeName());

        System.out.println("i will return a response message");
        StringBuilder responseContent = new StringBuilder();
        responseContent.append("this is a response text");
        ByteBuf responseByteBuf = Unpooled.copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);

        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,responseByteBuf);
        response.headers().set(CONTENT_TYPE,"text/html");
        response.headers().set(CONTENT_LENGTH,responseByteBuf.readableBytes());
        ctx.writeAndFlush(response);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    }
}
